#include <iostream>
#include<fstream>
#include "string.h"
#define byte char
#define writeFile "project1Bin.binf"
// 编码表达式
byte *encode(char *exprossions);
// 解码表达式
char *decode(byte *data);
char parityCheck(char data);
//奇偶校验
void printBinary(char data);
int writeEncode(byte *data);
byte *readAndDecode();
byte *readEncode(int byteNum);

//-------------------------------


// 编码表达式
byte *encode(char *exprossions)
{
    char b1[2] = {22, 22};
    char b2 = 0;
    b2 = (char)(strlen(exprossions) * 8);
    std::cout<<"len="<<(int)b2<<"\n";
    b2 = parityCheck(b2);
    int size = strlen(exprossions) + 3;
    byte *b3 = NULL;
    b3 =  new byte[size]; ;
    b3[0] = b1[0];
    b3[1] = b1[1];
    b3[2] = b2;
    for (int i = 0; i < strlen(exprossions); i++)
    {
        b3[i + 3] = parityCheck(exprossions[i]);
    }
    return b3;
}

// 解码表达式
char *decode(byte *data)
{
    std::cout << "decode!" << std::endl;
    return "encode";
}

char parityCheck(char data)
{
    //1.获得1数量
    int num = 0;
    for (int i = 0; i < 8; i++)
    {
        char temp = data & (1 << i);
        if (temp != 0)
        {
            //数量+1
            num++;
        }
    }
    // std::cout << "num:" << num << "\n";
    // 奇偶校验
    if (num % 2 == 0)
    {
        //如果最后一位是 1
        //1000 0000
        char temp = data & (1 << 7);
        if (temp != 0)
        {
            data &= (~(1 << 7));
        }
        else
        {
            data |= (1 << 7);
        }
    }
    return data;
}
void printBinary(char data)
{
    for (int i = 7; i >= 0; i--)
    {
        char temp = data & (1 << i);
        if (temp != 0)
        {
            std::cout << "1";
        }
        else
        {
            std::cout << "0";
        }
    }
    std::cout << "\n";
}
int writeEncode(byte *data)
{
    std::ofstream f(writeFile, std::ios::binary);
	if(!f)
	{
		std::cout << "创建文件失败" <<std::endl;
		return -1;
	}
	f.write(data, strlen(data));
	f.close();
    return 0;
}

byte *readAndDecode(){
	byte *h1 = NULL;
    h1 = new byte[2];
    byte *h2 = NULL;
    h2 = new byte[1];
	byte *d3 = NULL;
	std::ifstream f(writeFile, std::ios::binary);
	if(!f)
	{
		std::cout << "读取文件失败" <<std::endl;
		return d3;
	}
	f.read((byte*)h1,16);
	f.read((char*)h2,8);
    //解码奇偶校验
    int size = (int)(h2[0]& (~(1<<7)));
    //分配内存
    d3 = new byte[h2[0]];
    //读取负载
	f.read(d3,8*size);
    //关闭文件
	f.close();
    return d3;
}
byte *readEncode(int byteNum){
    byte *data = NULL;
    data = new byte[byteNum];
    std::ifstream f(writeFile, std::ios::binary);
    f.read(data,8*byteNum);
    f.close();
    return data;
}